package com.mycompany.app.hr.workflow.jbpm.support;

import java.io.InputStream;

import org.jbpm.graph.def.ProcessDefinition;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;

/**
 * NOTICE:本类代码参考及使用了spring-modules项目中jbpm31的源代码，在本工程中提供jbpm32的支持，
 * 感谢spring-modules项目组
 * 
 * @author Shawn.guo
 */
public class ProcessDefinitionFactoryBean implements FactoryBean,
        InitializingBean {
    private ProcessDefinition processDefinition;

    private Resource definitionLocation;

    public void setDefinitionLocation(Resource definitionLocation) {

        this.definitionLocation = definitionLocation;
    }

    public void afterPropertiesSet() throws Exception {

        if (this.definitionLocation == null)
            throw new FatalBeanException(
                    "Property [definitionLocation] of class ["
                            + ProcessDefinitionFactoryBean.class.getName()
                            + "] is required.");

        InputStream inputStream = null;
        try {
            inputStream = this.definitionLocation.getInputStream();
            this.processDefinition = ProcessDefinition
                    .parseXmlInputStream(inputStream);

        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    public Object getObject() throws Exception {

        return this.processDefinition;
    }

    public Class getObjectType() {

        return (processDefinition == null) ? ProcessDefinition.class
                : processDefinition.getClass();
    }

    public boolean isSingleton() {

        return true;
    }
}